const { pool } = require('../config/db');
const { auditLogService } = require('../services/auditLogService.uts');

/**
 * 添加审计日志
 * @param {Object} logData 日志数据对象
 * @param {number} logData.user_id 用户ID
 * @param {string} logData.action 操作类型
 * @param {Object} logData.details 操作详情
 * @param {string} logData.ip_address IP地址
 * @returns {Promise<Object>} 创建的日志对象
 */
async function addAuditLog(logData) {
  try {
    const { user_id, action, details, ip_address } = logData;
    
    // 验证数据
    if (!auditLogService.validateAuditLogData(logData)) {
      return {
        success: false,
        error: '审计日志数据无效'
      };
    }
    
    // 转换details对象为JSON字符串
    const detailsJson = typeof details === 'object' ? JSON.stringify(details) : details;
    
    // 插入审计日志
    const [result] = await pool.query(
      'INSERT INTO audit_logs (user_id, action, details, ip_address) VALUES (?, ?, ?, ?)',
      [user_id, action, detailsJson, ip_address]
    );

    return {
      success: true,
      id: result.insertId,
      timestamp: new Date()
    };
  } catch (error) {
    console.error('添加审计日志失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

/**
 * 获取用户登录历史
 */
async function getUserLoginHistory(req, res) {
  try {
    const userId = req.user.id; // 从认证中间件获取
    const { startDate, endDate, includeLogout } = req.query;

    // 解析includeLogout参数
    const shouldIncludeLogout = includeLogout !== 'false' && includeLogout !== '0';

    // 获取登录历史记录
    const loginHistory = await getLoginHistory(userId, startDate, endDate, shouldIncludeLogout);

    res.json({
      success: true,
      data: loginHistory
    });
  } catch (error) {
    console.error('获取登录历史失败:', error);
    res.status(500).json({
      success: false,
      message: '获取登录历史失败',
      error: error.message
    });
  }
}

/**
 * 获取用户的登录历史记录
 * @param {number} userId 用户ID
 * @param {string} startDate 开始日期 (YYYY-MM-DD)
 * @param {string} endDate 结束日期 (YYYY-MM-DD)
 * @param {boolean} includeLogout 是否包含退出登录记录
 * @returns {Promise<Array>} 登录历史记录数组
 */
async function getLoginHistory(userId, startDate, endDate, includeLogout = true) {
  try {
    // 构建查询条件
    const conditions = ['user_id = ?'];
    const params = [userId];
    
    // 如果需要包含退出登录记录，则查询login和logout动作
    if (includeLogout) {
      conditions.push('(action = "login" OR action = "logout")');
    } else {
      conditions.push('action = "login"');
    }
    
    if (startDate) {
      conditions.push('DATE(timestamp) >= ?');
      params.push(startDate);
    }
    
    if (endDate) {
      conditions.push('DATE(timestamp) <= ?');
      params.push(endDate);
    }
    
    // 查询登录历史
    const [logs] = await pool.query(
      `SELECT id, user_id, action, details, ip_address, timestamp 
       FROM audit_logs 
       WHERE ${conditions.join(' AND ')} 
       ORDER BY timestamp DESC 
       LIMIT 50`,
      params
    );
    
    // 使用UTS服务处理结果
    return auditLogService.processLoginHistory(logs);
  } catch (error) {
    console.error('获取登录历史失败:', error);
    return [];
  }
}

module.exports = {
  getUserLoginHistory,
  addAuditLog
};